/**
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package mobcam;

import java.io.IOException;
import javax.microedition.lcdui.StringItem;
import javax.microedition.media.MediaException;

/**
 *
 * @author Knut Magne Solem
 */
public class CameraSnapshotRunner implements Runnable {

    private StringItem statusField;
    private CameraController cameraController;
    private ImageUploader uploader;
    private boolean running = true;
    private long minutesBetweenSnapshots;

    public CameraSnapshotRunner(StringItem statusField, CameraController cameraController, ImageUploader uploader, long minutesBetweenSnapshots) {
        this.statusField = statusField;
        this.cameraController = cameraController;
        this.uploader = uploader;
        this.minutesBetweenSnapshots = minutesBetweenSnapshots;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    public void run() {
        while (running) {
            long startTime = System.currentTimeMillis();
            try {
                statusField.setText("Snapshotting...");
                byte[] image;
                if (cameraController.getCapabilities().length() > 100){
                    image = cameraController.getSnapshot();
                }else{
                    image=getMockImage();
                }
                statusField.setText("Uploading " + image.length + " bytes...");
                uploader.httpUpload(image);
            } catch (IOException ex) {
                statusField.setText("Exc: " + ex.getMessage());
            } catch (MediaException ex) {
                statusField.setText("Exc: " + ex.getMessage());
            }
            long duration = System.currentTimeMillis() - startTime;
            try {
                Thread.sleep(minutesBetweenSnapshots * 60 * 1000 - duration);
            } catch (InterruptedException ex) {
            }
        }
    }

    private byte[] getMockImage() {
        byte[] data = new byte[5500];
        for (int i=0;i<data.length;i++){
            data[i] = 125;
        }
        return data;
    }
}